﻿CREATE PROCEDURE [dbo].[usp_insert_AlertSubscriptionHistory]
(
	@AlertSubscriptionHistoryID	    uniqueidentifier
	,@AlertSubscriptionID			uniqueidentifier
	,@AlertHistoryID				uniqueidentifier
	,@Subscriber					varchar(255)
	,@IsGroup						bit
	,@CustomEmail					varchar(255)
	,@LastFired						datetime
	,@Debug							bit			   = 0
)
AS

/****************************************************************************
Name: usp_insert_AlertSubscriptionHistory.sql
Description: 
*****************************************************************************/
SET NOCOUNT ON;

-- Bootstrap
DECLARE @DebugPrefix       varchar(10);
DECLARE @ErrorCode         int;

SET @ErrorCode          = 0;
SET @DebugPrefix        = '>>> DEBUG: ';

-- Print parameters
IF (@Debug > 0)
BEGIN
	PRINT @DebugPrefix + '@AlertHistoryID = '	+ CONVERT(varchar, @AlertHistoryID);
PRINT @DebugPrefix + '@Subscriber = '	+ @Subscriber;
PRINT @DebugPrefix + '@IsGroup = '	+ CONVERT(varchar, @IsGroup);
END;



INSERT INTO [dbo].[AlertSubscriptionHistory]
           ([AlertSubscriptionHistoryID]
			,[AlertHistoryID]
			,[Subscriber]
			,[IsGroup]
			,[CustomEmail]
            ,[InsertedDate]
			)
     VALUES
           (@AlertSubscriptionHistoryID          
			,@AlertHistoryID
			,@Subscriber
			,@IsGroup
			,@CustomEmail
			,GetUTCDate()
           )


UPDATE dbo.AlertSubscription
SET LastFired = @LastFired
WHERE AlertSubscription.AlertSubscriptionID = @AlertSubscriptionID

-- CHECK FOR ERROR
SET @ErrorCode = @@Error;

IF (@ErrorCode <> 0) GOTO ERROR_HANDLER;

RETURN 0;

-- Handles errors.
ERROR_HANDLER:
IF (@ErrorCode <> 0)
BEGIN
    IF (@Debug > 0) 
		BEGIN
			PRINT @DebugPrefix + 'Error Code = ' + CAST(@ErrorCode AS varchar(10)) + ' occurred while executing dbo.usp_insert_AlertSubscriptionHistory.';
			RETURN @ErrorCode
		END

    -- Don't return any evidence of what specific error occurred, i.e. 
    -- we want to ward off potential hackers.
    RETURN 1;
END;

SET NOCOUNT OFF;
